//
// Created by htlin on 2021/3/1 0001.
//

#include "Thread.h"
#include "pthread.h"

class ThreadPrivateData {
public:
    uv_thread_t *handle;
    bool isRunning;
};

Thread::Thread() {
  data = std::make_unique<ThreadPrivateData>();
  data->isRunning = false;

  initializeData();
}

Thread::~Thread() {
  free(data->handle);
}

void Thread::run() {

}

void Thread::start() {
  prepare();

  uv_thread_create(data->handle, Thread::threadCB, static_cast<void *>(this));
  pthread_detach((pthread_t) (*(data->handle)));
}

void Thread::initializeData() {
  data->handle = static_cast<uv_thread_t *>(malloc(sizeof(uv_thread_t)));
}

void Thread::threadCB(void *data) {
  auto *thisPointer = static_cast<Thread *>(data);
  thisPointer->data->isRunning = true;
  thisPointer->run();
  thisPointer->data->isRunning = false;
}

uv_thread_t Thread::getThreadId() {
  return uv_thread_self();
}

void Thread::prepare() {

}

bool Thread::isRunning() const {
  return data->isRunning;
}
